<template>
  <div>
    <section>
      <el-form
        ref="form"
        :model="queryForm"
        label-width="47px"
        :inline="true"
        class="queryForm adjustCondition"
      >
        <el-row>
          <el-form-item label="供应商名称:" label-width="89px">
            <el-input v-model.trim="queryForm.name" size="small" clearable placeholder="请输入供应商名称"></el-input>
          </el-form-item>

          <el-form-item label="原料目录:" label-width="75px">
            <section style="width:230px">
              <treeselect class="treeselect-adjust" placeholder="请选择原料目录" size="small" :disable-branch-nodes="true" v-model="queryForm.productCategoryId"  :multiple="false" :options="options"  :normalizer="normalizer"/>
            </section>
          </el-form-item>
            <el-form-item label="状态:">
                <el-select clearable v-model="queryForm.checkedState" placeholder="全部">
                    <el-option
                        v-for="item in  $dictUtils.getDictList('state')"
                        v-if="item.value !== '-1'"
                        :key="item.value"
                        :label="item.label"
                        :value="Number(item.value)">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="地区:" >
            <section style="width:320px">
              <Area ref="area"  v-model="queryForm.areaCode" @getArea="getArea1"></Area>
            </section>
          </el-form-item>

          <el-form-item>
            <div class="but-container">
              <el-button class="search-btn" type="primary" size="small" @click="getList(page, 2,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState,queryForm.areaCode,queryForm.productCategoryId)">查询</el-button>
              <el-button size="small" @click="reset">重置</el-button>
            </div>
          </el-form-item>
        </el-row>

      </el-form>
    </section>
    <div>
      <el-button type="primary" size="small"  @click="add" v-if="hasPermission('company:company:add')">新增</el-button>
<!--      <el-button type="default" size="small"-->
<!--                 @click="exportExcel(page, 2,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState,queryForm.areaCode,queryForm.productCategoryId)" style="margin-left: 15px">-->
<!--          导出-->
<!--      </el-button>-->
      <section class="right-but adjustRight-but" style="display:flex;margin-bottom:0px">
          <el-button type="text"  style="cursor:pointer;" @click="exportExcel(page, 2,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState,queryForm.areaCode,queryForm.productCategoryId)">
              <img style="width:44px;height:36px;" src="~@/assets/img/export.png" >
          </el-button>
        <el-button type="text" @click="getList(page, 2,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState)">
          <img style="width:44px;height:36px;" src="~@/assets/img/refresh.png" >
        </el-button>
        <PopoverBut :checkedProps="checkedProps"  :options="checkOptions" @getCheckeds="handlerCloumn"></PopoverBut>

      </section>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%; margin-top: 10px"
      border
      :header-cell-style="{
        'background-color': '#eeeeee !important',
      }"
      :row-class-name="tableRowClassName"
      @sort-change="sortthiscolumn"
    >
      <el-table-column type="index" label="序号" width="70" align="center">
        <template slot-scope="scope">
          <span>{{
              (page.pageNo - 1) * page.pageSize + scope.$index + 1
            }}</span>
        </template>
      </el-table-column>
        <el-table-column prop="types" label="类型" width="100px" sortable="custom">
          <template slot-scope="scope">
            <section>
              {{$dictUtils.getDictLabel("companyType", scope.row.types, "")}}
            </section>
          </template>
        </el-table-column>

        <el-table-column prop="names" label="供应商简称"  min-width="200" sortable="custom" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="view(scope.row)">{{scope.row.names}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="detailAddress" min-width="300" label="收货地址" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <section>{{scope.row.contactName}} {{scope.row.contactPhone}} {{scope.row.detailAddress}}</section>
          <section>
            <el-link
              type="primary"
              :underline="false"
              @click="otherAddress(scope.row)"
            >编辑收货地址({{scope.row.addressCount}})</el-link
            >
          </section>
        </template>
      </el-table-column>
      <el-table-column prop="productNames" label="原料目录" min-width="250" sortable="custom" :show-overflow-tooltip="true">
          <template slot-scope="scope">
              {{scope.row.productNames | noValue}}
          </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" sortable="custom" width="100">
        <template slot-scope="scope">
          <section class="activate-state" v-if="scope.row.state===1">
            <i></i>
            {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
          </section>
          <section class="inactive-state" v-else>
            <i></i>
            {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
          </section>
        </template>
      </el-table-column>
      <span v-for="(item,index) in checkedProps" :key="index">
                <el-table-column prop="fullNames" :label="item"  v-if="item==='供应商名称'" width="280" sortable="custom" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-link v-if="scope.row.fullNames" type="primary" :underline="false" @click="view(scope.row)">{{scope.row.fullNames}}</el-link>
            <span v-else>--</span>
        </template>
      </el-table-column>
         <el-table-column  prop="idCard" :label="item" min-width="220" v-if="item==='身份证号'">
             <template slot-scope="scope">
                 {{scope.row.idCard | noValue}}
             </template>
         </el-table-column>
         <el-table-column  prop="codes" :label="item"  min-width="210" v-if="item==='统一社会信用代码'">
             <template slot-scope="scope">
                {{scope.row.codes | noValue}}
            </template>
         </el-table-column>
  <el-table-column prop="createBy.loginName"  min-width="110" :label="item" v-if="item ==='创建人'">
              <template slot-scope="scope">
                  <span v-if="scope.row.createBy">{{scope.row.createBy.loginName | noValue}}</span>
              </template>
          </el-table-column>
        <el-table-column prop="createDate" :label="item"  width="140" v-if="item === '创建时间'">
            <template slot-scope="scope">
                {{scope.row.createDate | noValue}}
            </template>
        </el-table-column>
          <el-table-column prop="updateBy.loginName"  min-width="120" :label="item" v-if="item ==='上次操作人'">
              <template slot-scope="scope">
                  {{scope.row.updateBy.loginName | noValue}}
              </template>
          </el-table-column>
        <el-table-column prop="updateDate" :label="item" width="140" v-if="item === '上次操作时间'">
            <template slot-scope="scope">
                {{scope.row.updateDate | noValue}}
            </template>
        </el-table-column>

      </span>
      <el-table-column prop="address" label="操作" width="176px">
        <template slot-scope="scope">
          <template v-for="item in $dictUtils.getDictList('state')">
            <el-link type="primary" v-if="item.value !=='-1'&& item.value!==(scope.row.state+'')" :underline="false" @click="isRepeat(item.value,scope.row)"  :disabled="(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state"
            >{{item.label}}
            </el-link>
          </template>
<!--          <el-link type="primary" :underline="false" @click="view(scope.row)">详情</el-link>-->
          <el-link v-if="hasPermission('company:company:edit')" type="primary" :underline="false" @click="edit(scope.row)"
          >修改</el-link
          >
          <el-link v-if="hasPermission('company:company:delete')"
                   type="primary"
                   :underline="false"
                   @click="isCheck(scope.row)"
          >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="page.pageSize"
      :current-page="page.pageNo"
      layout="total,sizes,prev, pager, next, jumper"
      :total="page.total"
    >
    </el-pagination>
    <CrmForm
      ref="crmForm"
      @refreshDataList="getList(page, 2, orderBy.name, orderBy.method)"
    ></CrmForm>
    <AddressForm ref="addressForm" @refreshDataList="getList(page, 2, 'names', 'asc')"></AddressForm>
  </div>
</template>
<script>
  import { getList, delCrm, editState, getById ,isCheck, getTreeData} from '@/api/market/crm.js'
  import CrmForm from './crmForm'
  import AddressForm from './addressForm'
  import PopoverBut from '@/components/button/popoverBut'
  import Area from '@/components/area/area'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  const options1 = []
  const cityOptions = ['上海', '北京']
  export default {
    components: {
      CrmForm,
      AddressForm,
      PopoverBut,
      Area,
      Treeselect
    },

    data () {
      return {
        msg: '',
        checkedProps: options1,
        ShowCloum: {createDate: ''},
        options: [],
        checkOptions: [
          {label: '供应商名称', key: 'fullNames'},
          {label: '统一社会信用代码', key: 'codes'},
          {label: '身份证号', key: 'idCard'},
          { label: '创建人', key: 'createBy.loginName' },
          { label: '创建时间', key: 'createDate' },
          { label: '上次操作人', key: 'updateBy.loginName' },
          { label: '上次操作时间', key: 'updateDate' },
        ],
        tableData: [],
        orderBy: {
          name: 'update_date',
          method: 'desc'
        },
        loading: false,
        page: {
          pageSize: 10,
          pageNo: 1,
          total: 0
        },
        props: 1,
        queryForm: {
          checkedState: '',
          areaCode: '',
          productCategoryId: null,
          productCategoryName: '',
          name: ''
        },
        checkedState: [],
        cities: cityOptions
      }
    },
    methods: {
      normalizer (node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      getTreeData (id,types) {
        getTreeData({id: id, types: types}).then((res) => {

          if (res.data.code === '200') {
            console.log(res.data.result)
            this.options = res.data.result
            this.exec(this.options)
            console.log(this.options)
          }
        });
      },
      //递归删除空数组
      exec(array) {
        array.forEach(item => {
          if (item.children.length === 0) {
            delete item.children
          } else {
            this.exec(item.children)
          }
        })
      },
      changeValue(val) {
        this.$nextTick(()=>{
          this.$refs["editForm"].validateField("productCategoryId");
        })
      },
      getArea1 (e) {
        if (e.province !== '' || e.city !== '' || e.district !== '') {
          this.queryForm.areaCode = JSON.stringify(e)
        } else {
          this.queryForm.areaCode = ''
        }
      },
      // 校验：该客户信息是否已被使用
      isCheck (row) {
        isCheck({
          id: row.id
        }).then((res) => {
          if (JSON.stringify(res.data.result)!=="[]") {
            this.$notify.error({
              title: '错误',
              message: '该客户信息已被使用，不允许删除！'
            })
          } else {
            this.delCrm(row.id)
          }
        });

      },
      // 获取列表带分页
      getList (params, props, orderName, orderByAORC, queryNames, queryState, areaCode,productCategoryId) {
        console.log(this.queryForm.productCategoryId)
        this.loading = true
        getList({
          pageSize: params.pageSize,
          pageNo: params.pageNo,
          props: props,
          orderBy: orderName,
          orderByAORC: orderByAORC,
          names: queryNames,
          state: queryState,
          countyCode: areaCode,
          productCategoryId: productCategoryId
        }).then((res) => {
          if (res.data.code === '200') {
            this.tableData = res.data.result.list
            this.page.total = res.data.result.count
          }
          this.loading = false
        })
      },
      // 删除客户
      delCrm (ids) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          delCrm ({
            ids: ids
          }).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '已删除!'
              })
              this.getList(this.page,2,this.orderBy.name,this.orderBy.method)
            }
          })
        });
      },
      // 添加
      add () {
        this.$refs.crmForm.init('add')
      },
      // 编辑
      edit (row) {
        getById({id: row.id}).then((res) => {
          if (res.data.code === '200') {
            let editForm = {}
            editForm.types = res.data.result.types
            editForm.id = res.data.result.id
            editForm.addressId = res.data.result.addressId
            editForm.names = res.data.result.names
            editForm.fullNames = res.data.result.fullNames
            editForm.codes = res.data.result.codes
            editForm.idCard = res.data.result.idCard
            editForm.contactName = res.data.result.contactName
            editForm.contactPhone = res.data.result.contactPhone
            editForm.detailAddress = res.data.result.detailAddress
              editForm.lat = res.data.result.lat
              editForm.lng = res.data.result.lng
            editForm.countyCode = res.data.result.countyCode
            if (editForm.countyCode === 'undefined') {
              editForm.countyCode = ''
            }
            this.$refs.crmForm.init('edit', editForm)
          } else {
            this.$message({
              type: 'error',
              message: res.data.message
            })
          }
        })
      },
      // 查看详情
      view (row) {
        let editForm = {}
        editForm.types = row.types
        editForm.id = row.id
        editForm.addressId = row.addressId
        editForm.names = row.names
        editForm.fullNames = row.fullNames
        editForm.codes = row.codes
        editForm.idCard = row.idCard
        editForm.contactName = row.contactName
        editForm.contactPhone = row.contactPhone
        editForm.detailAddress = row.detailAddress
        editForm.countyCode = row.countyCode
          editForm.lng = row.lng
          editForm.lat = row.lat
        this.$refs.crmForm.init('view', editForm)
      },

      // 停用确认
      isRepeat (event, row) {
        if (row.state === 1) {
          console.log(row)
          this.msg = '停用后，该客户将不可被使用，确认停用吗？';
          this.editState(event, row.id)

        } else {
          this.msg = '您是否要' + this.$dictUtils.getDictLabel("state", event, "") + '?'
          this.editState(event, row.id)
        }
      },
      // 改变客户状态
      editState (state, id) {
        this.$confirm(this.msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          editState({id: id, state: state}).then(res => {
            if (res.data.code === '200') {
              this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
              this.$message({
                type: 'success',
                message: '状态修改成功'
              })
            }
          })
        })
      },

      // 导出
      exportExcel (params, props, orderName, orderByAORC, queryNames, queryState, areaCode,productCategoryId) {
        this.$http({
          method: 'get',
          url: '/basis/sales/company/export',
          params: {
            pageSize: params.pageSize,
            pageNo: params.pageNo,
            props: props,
            orderBy: orderName,
            orderByAORC: orderByAORC,
            names: queryNames,
            state: queryState,
            countyCode: areaCode,
            productCategoryId: productCategoryId
          },
          responseType: 'blob'
        }).then(response => {
          if (!response) {
            return
          }
          let link = document.createElement('a')
          link.href = window.URL.createObjectURL(new Blob([response.data]))
          link.target = '_blank'
          let filename = response.headers['content-disposition']
          link.download = decodeURI(filename)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // eslint-disable-next-line handle-callback-err
        }).catch((error) => {

        })
      },
      // 是否显示某列数据
      handlerCloumn (e) {
        this.checkedProps = e
        // console.log(e)
      },
      // 重置查询条件
      reset () {
        this.queryForm = {}
        this.$nextTick(()=> {
          this.$refs['area'].province = ''
          this.$refs['area'].city = ''
          this.$refs['area'].district = ''
        })
          this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
      },
      otherAddress (row) {
        this.$refs.addressForm.init('view', row)
      },
      // 排序
      sortthiscolumn (a) {
        console.log(a)
        this.orderBy.name = a.prop
        this.page.pageNo = 1
        if (a.order === 'ascending') {
          this.orderBy.method = 'asc'
        } else {
          this.orderBy.method = 'desc'
        }
        this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
      },
      handleSizeChange (e) {
        this.page.pageSize = e
        this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
      },
      handleCurrentChange (e) {
        this.page.pageNo = e
        this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
        console.log(e)
      },
      tableRowClassName ({ row, rowIndex }) {
        if (rowIndex % 2 === 1) {
          return 'warning-row'
        } else {
          return 'success-row'
        }
      }
    },
    mounted () {
      this.getList(this.page, 2, this.orderBy.name, this.orderBy.method)
      this.getTreeData(0,1)
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep .el-input--small .el-input__inner {
    height: 36px;
    line-height: 32px;
    width: 180px;
  }
  ::v-deep .queryForm {
    .el-radio{
      margin-right: 15px;
    }
    .el-row:first-child{
      .el-input__inner{
        min-width: 230px;
      }
        .el-form-item:last-child{
            .el-input__inner{
                min-width: 175px;
                width: 175px;
            }
        }
    }
    .el-form-item{
      margin-bottom: 20px;
      margin-right: 50px;
    }
    .vue-treeselect__menu{
      overflow: auto;
    }
  }
  .right-but {
    float: right;
  }

  ::v-deep .el-table{
      .el-tooltip{
          section{
              overflow: hidden;
              text-overflow: ellipsis;
          }
      }
  }
</style>
